import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_model/home/home_tabs_entity.dart';
import 'package:tiktokadult/hj_model/home/module_detail_model.dart';
import 'package:tiktokadult/hj_model/splash/ads_model.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/tools_base/global_store/local_ads_info_store.dart';

import '../../../tools_base/ad_insert_manager.dart';
import '../../main_page/provider/bottom_bar_provider.dart';

const Interval = 4;

abstract class HomeSubLogic extends GetxController {
  /// 自己在父级的位置
  final int index;
  final ModuleData module;

  int get intervalAdGap => 6;
  bool isDark = false;

  HomeSubLogic(this.module, {this.index = 0, this.isDark = false});

  List dataSource = []; // 页面数据
  RefreshController? controller;
  int page = 1;

  bool isLoading = true; // 是否展示排序

  /// 页面排序
  ///1 最新更新， 2本周最热， 3 最多观看， 4 十分钟以上
  List<String> get sortTitles => ['热门推荐', '最新上架', '最多观看', '最多收藏'];
  int sort = 1;
  List<int> get sortNetParam => [1, 2, 3, 4];

  /// 专题数据
  List<AllSection> specialTopics = [];

  /// 是否拿过广告了
  bool hasFetchADs = false;

  /// 广告数据
  List<AdsInfoModel> listADS = [];

  /// 是否展示预售
  bool showPresale = false;

  int get advPosition => 8;

  RxBool showFAImg = true.obs; // 滑动显示或隐藏悬浮图标(预售一直显示,不处理)
  RxBool isGridStyle = true.obs; // type=1 展示切换样式
  String styleKey = 'list_style'; //切换样式动画key

  final sctrl = ScrollController();

  @override
  void onInit() {
    super.onInit();
    fetchListADs();
  }

  @override
  void onReady() {
    super.onReady();
    if (isDark) {
      DarkwebBottomProvider().setSrollController(
        index,
        controller: sctrl,
      );
    } else {
      HomeBottomProvider().setSrollController(
        index,
        controller: sctrl,
      );
    }
    onInitData();
  }

  void onInitData() {
    isLoading = true;
    update();
    fetchPageData(sort);
  }

  void onRefreshData() {
    fetchPageData(sort);
  }

  void loadMoreData() {
    fetchPageData(sort, pageNumber: page + 1);
  }

  void sortMenuEvent(int index) {
    sort = sortNetParam[index];
    onInitData();
  }

  Future<ModuleDetailModel?> fetchPageData(int sortValue, {int pageNumber = 1, int pageSize = 10}) async {
    // try {
    //   final res = await VidService.getModuleDetail(
    //     module.id ?? '',
    //     pageNumber: pageNumber,
    //     pageSize: pageSize,
    //     moduleSort: sortValue,
    //   );
    //   return res;
    // } catch (e) {
    //   debugLog(e);
    //   return null;
    // }
  }

  /// 获取广告
  fetchListADs() async {
    final adsList = await getAdvByType(advPosition);
    listADS.clear();
    listADS.addAll(adsList);
    hasFetchADs = true;
  }

  /// 插入广告
  insertListAdsToList() async {
    if (dataSource.length < intervalAdGap) return;
    if (!hasFetchADs) await fetchListADs();
    if (listADS.isEmpty) return;

    dataSource.removeWhere((element) => element.isRandomAd());
    final tempM = []..addAll(dataSource);
    for (var i = intervalAdGap; i < tempM.length; i += intervalAdGap) {
      int index = i ~/ intervalAdGap;
      print('index  ------ $index           ${i + (index - 1)}    ${dataSource.length}');
      dataSource.insert(i + (index - 1), VideoModel()..randomAdsInfo = listADS[(index - 1) % listADS.length]);
    }
  }

  onTooleAction() {
    isGridStyle.value = !isGridStyle.value;
    styleKey = isGridStyle.value ? 'grid_style' : 'list_style';

    update();
  }
}

// 专题
class SpecialController extends HomeSubLogic {
  SpecialController(super.module, {super.index, super.isDark});

  @override
  int get intervalAdGap => 8;

  @override
  onInit() {
    super.onInit();
  }

  @override
  Future<ModuleDetailModel?> fetchPageData(int sortValue, {int pageNumber = 1, int pageSize = 10}) async {
    final res = await VidService.getModuleDetail(module.id ?? '', moduleSort: sortValue, pageNumber: pageNumber, pageSize: pageSize);

    if (sort != sortValue) return null;
    page = pageNumber;
    isLoading = false;

    controller?.refreshCompleted();
    if (res?.hasNext ?? false) {
      controller?.loadComplete();
    } else {
      controller?.loadNoData();
    }
    if (pageNumber == 1) {
      dataSource.clear();
      specialTopics.clear();
      specialTopics.addAll(res?.allSection ?? []);
    }
    final list = List<VideoModel>.from(dataSource);

    list.addAll(res?.allVideoInfo ?? []);

    AdInsertManager.video(list, listADS, adGap: 8);

    dataSource = list;

    update();
    return res;
  }
}

//动漫和漫画相关亚模块
class ACGController extends HomeSubLogic {
  ACGController(super.module, {super.index, super.isDark});
  @override
  int get intervalAdGap => 8;

  @override
  List<String> get sortTitles => ['最新更新', '本周最热', '最多点赞', '最多观看'];

  @override
  List<int> get sortNetParam => [1, 2, 3, 4];

  @override
  onInit() {
    super.onInit();
    HomeBottomProvider().setSrollController(index, controller: sctrl);
  }

  @override
  Future<ModuleDetailModel?> fetchPageData(
    int sortValue, {
    int pageNumber = 1,
    int pageSize = 15,
  }) async {
    final res = await VidService.getModuleDetail(
      module.id ?? '',
      moduleSort: sortValue,
      pageNumber: pageNumber,
      pageSize: pageSize,
    );

    if (sort != sortValue) return null;
    page = pageNumber;
    isLoading = false;

    controller?.refreshCompleted();
    res?.hasNext == true ? controller?.loadComplete() : controller?.loadNoData();
    if (pageNumber == 1) {
      dataSource.clear();
      specialTopics.clear();
      specialTopics.addAll(res?.allSection ?? []);
    }
    final list = List<CartoonMediaInfo>.from(dataSource);

    list.addAll(res?.allMediaInfo ?? []);

    //插入广告
    // AdInsertManager.video(list, listADS, adGap: 8);

    dataSource = list;

    update();
    return res;
  }
}

/// 实例话所有的样式控制器
T instanceController<T>(ModuleData module, int index, bool isDark) {
  final type = T.toString();
  if (type == 'SpecialController') return SpecialController(module, index: index, isDark: isDark) as T;
  if (type == 'ACGController') return ACGController(module, index: index, isDark: isDark) as T;
  // if (type == 'NewOrFeaturedController') return NewOrFeaturedController(module) as T;
  // if (type == 'DeepWebController') return DeepWebController(module) as T;
  throw '$type 没有对应类型';
}
